package com.seednia.module.core.category.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import au.com.bytecode.opencsv.CSVReader;

import com.seednia.foundation.framework.dto.QueryParams;
import com.seednia.foundation.framework.service.RequestContext;
import com.seednia.foundation.framework.service.RequestContextFactory;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.util.HierarchicalTask;
import com.seednia.module.core.category.dto.CategoryCriteria;
import com.seednia.module.core.category.dto.CategoryDto;
import com.seednia.module.core.xport.XportException;

public class PopulateCategoryTask extends HierarchicalTask {

	ICategoryService svc = null; 
	
	@Before
	public void initialize() {
		ServiceContainer.getInstance().loadAppContext("applicationContext-test.xml");
		
		
	}
	
	public ICategoryService getCategoryService()
	{
		if (svc == null)
			svc = ServiceContainer.getInstance().getByType(ICategoryService.class);
		
		return svc;
	}
	
	@Test
	public void populate() throws Exception
	{	
		execute(null);
	}
	
	
	public void execute(Map<String, Object> context) throws Exception
	{	
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/seednia/module/core/category/data-categories.csv");
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		CSVReader csvReader = new CSVReader(reader);
		
		int lineNum = 0;
		String[] tokens = null;
		
		// First line is comment
	    if ((tokens = csvReader.readNext()) != null)
	    	lineNum++;
	    else 
	    	throw new XportException("Meta header line not found");
		
	    while ((tokens = csvReader.readNext()) != null) {
			lineNum++;
			CategoryCriteria criteria = new CategoryCriteria(tokens[0], tokens[1], tokens[2]);
			
			RequestContext requestContext = RequestContextFactory.createSystemRequestContext(); 
			List<CategoryDto> retrieved = svc.getCategoryList(requestContext, criteria, new QueryParams(0, 1));
			if (retrieved == null || retrieved.size() == 0) {
				CategoryDto dto = new CategoryDto(tokens[0], tokens[1], tokens[2], tokens[2]);
				Assert.assertNotNull("insertCategory returned null at line "+lineNum, svc.insertCategory(requestContext, dto ));
			}
	    }
		
	}
}
